package com.zy.socket.exampls;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author Gong
 * @Description 3.从客户端发送文件给服务端，服务端保存到本地。并返回“发送成功”给客户端。并关闭相应的连接
 * @dATE 2021/12/19 10:41
 **/
public class Server3 {
    public static void main(String[] args) {
        InputStream inputStream = null;
        Socket accept =null;
        ServerSocket serverSocket =null;
        try {
             serverSocket = new ServerSocket(8989);
             accept = serverSocket.accept();
            System.out.println(accept);
            //获取流进行操作
             inputStream = accept.getInputStream();
             String filePath = "d:/temp/java_1.png";
            FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
            byte[] b = new byte[1024];
            int len;
            while ((len=inputStream.read(b))!=-1){
                fileOutputStream.write(b,0,len);
            }

            OutputStream outputStream = accept.getOutputStream();
            outputStream.write(("我是服务器，接收文件成功，保存路径为"+filePath).getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept!=null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
